package com.tec.security.utils.file;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileUploadService {
    @Value("${filePath.basePath}")
    private String basePath;
    @Value("${filePath.uploadPath}")
    private String uploadPath;
    public FileResult fileUpload(MultipartFile multipartFile, HttpServletRequest request){
        try{
            String realFileName=multipartFile.getOriginalFilename();
            assert realFileName != null;
            String fileSuffix=realFileName.substring(realFileName.lastIndexOf("."));
            String newFileName= UUID.randomUUID().toString().replace("-","")+fileSuffix;
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd");
            String datePath=simpleDateFormat.format(new Date());
            String serverPath=uploadPath;
            File file=new File(serverPath,datePath);
            if(!file.exists()){
                file.mkdirs();
            }
            File fileName=new File(file,newFileName);
            multipartFile.transferTo(fileName);
            String url=basePath+"file/images/"+datePath+"/"+newFileName;
            Map<String,Object> result=new HashMap<>();
            result.put("url",url);
            return new FileResult(0,"上传成功",result);
        } catch (IOException e) {
            return new FileResult(1,"上传失败",null);
        }
    }
}
